/*
 * Copyright © 2012 by PropSage Pte Ltd. 
 * All Rights Reserved.
 * licensing@propsage.com
 * http://www.propsage.com/terms.html
 * 
 * @author Poh Nean
 */
propsage.namespace("modules.admin.templates");


modules.admin.templates.index = (function($, ui){
	var currentPage = 1, widgetId = 0;
	var name = 'Untitled Document'; 
	var type = 'Factsheet';
	var selectedTool, selectedWidget;
	
	var settings = {};
	var defaultSettings = {
		dpi: 96,
		inchesPerMm: 0.0393701,
		dpm: 3.7795296,
		page: {
			height: 297, // mm
			width: 210,
			marginTop: 20,
			marginRight: 20,
			marginBottom: 30,
			marginLeft: 20
		},
		header: {
			height: 20,
			marginTop: 10
		},
		footer: {
			height: 30,
			marginBottom: 10
		}
	};
	
	var $editor, $toolbar, $overlay, $content;
	
	var tools = {
		addpage: {
			type: 'button',
			title: 'Add Page',
			action: actionAddPage
		},			
		//		pagesettings: {
		//			type: 'button',
		//			title: 'Page Settings',
		//			action: actionPageSettings
		//		},
		portrait: {
			type: 'button',
			title: 'Portrait',
			action: actionPortrait
		},
		landscape: {
			type: 'button',
			title: 'Landscape',
			action: actionLandscape
		},
		separator1: {
			type: 'separator'
		},	
		textbox: {
			type: 'button',
			title: 'Insert Textbox',
			action: actionInsertTextbox
		},
		image: {
			type: 'button',
			title: 'Insert Image',
			action: actionInsertImage
		},
		logo: {
			type: 'button',
			title: 'Insert Logo',
			action: actionInsertLogo
		},
		//		table: {
		//			type: 'button',
		//			title: 'Insert Table',
		//			action: actionInsertTable
		//		},
		//		floorplan: {
		//			type: 'button',
		//			title: 'Insert Floorplan',
		//			action: actionInsertFloorplan
		//		},
		separator2: {
			type: 'separator'
		},
		save: {
			type: 'button',
			title: 'Save',
			action: actionSave
		},
		preview: {
			type: 'button',
			title: 'Preview',
			action: actionPreview
		}
	};
	
	var widgets = [];
	
	function createWidget(data) {
		if (modules.admin.templates.widgets[data.type] != null) {
			var widgetClass = modules.admin.templates.widgets[data.type];
			var widget = new widgetClass(data);
			
			widget.container.appendTo($overlay);
		}
	}
	
	function contentHeight($el) {		
		var $checkHeight = $('<div id="checkHeight"></div>');		
		$checkHeight.css({
			'visibility': 'none'
		});
		$checkHeight.width($el.width());
		$checkHeight.html($el.html());
		$('body').append($checkHeight);
		
		var height = $checkHeight.height();
		$checkHeight.remove();
		
		return height;
	}
	
	function actionAddPage() {
		console.log('add page');
	}
	
	function actionPageSettings() {
		console.log('page settings');
	}
	
	function actionInsertTextbox() {				
		createWidget({
			'type': 'Textbox',
			'options': {
				'page': currentPage,
				'x': getDefaultX(),
				'y': getDefaultY()
			}
		});
	}
	
	function actionInsertImage() {						
		createWidget({
			'type': 'Image',
			'options': {
				'page': currentPage,
				'x': getDefaultX(),
				'y': getDefaultY(),
				'width': 100,
				'height': 100
			}
		});
	}
	
	function actionInsertLogo() {						
		createWidget({
			'type': 'Image',
			'options': {
				'page': currentPage,
				'src': agencyLogo,
				'x': getDefaultX(),
				'y': getDefaultY(),
				'width': agencyLogoWidth,
				'height': agencyLogoHeight
			}
		});
	}
	
	function actionPortrait() {
		var currentWidth = settings.page.width;
		var currentHeight = settings.page.height;
		
		if (currentWidth > currentHeight) {
		
			settings.page.width = currentHeight;
			settings.page.height = currentWidth;
		
			$('#pages, #editor').width(settings.page.width * settings.dpm);
			$('#pages, #editor').height(settings.page.height * settings.dpm);
		}
	}
	
	function actionLandscape() {
		var currentWidth = settings.page.width;
		var currentHeight = settings.page.height;
		
		if (currentWidth < currentHeight) {
		
			settings.page.width = currentHeight;
			settings.page.height = currentWidth;
		
			$('#pages, #editor').width(settings.page.width * settings.dpm);
			$('#pages, #editor').height(settings.page.height * settings.dpm);
		}
	}
	
	function actionInsertTable() {
		console.log('insert table');
	}
	
	function actionInsertFloorplan() {
		console.log('insert floorplan');
	}
	
	function actionLoad() {
		console.log('load');
	}
	
	function actionSave() {
		var data = {};
		
		data.name = name;
		data.type = type;
		
		// page settings
		data.settings = settings;
		
		// widgets
		var $widget, widgetData, widgetOptions, matrix;
		
		data.widgets = [];
		$('.widget').each(function(i, widget) {
			$widget = $(widget);
			pos = $widget.position();
			
			var m;
			var css = $widget.css("-webkit-transform") ||
			$widget.css("-moz-transform")    ||
			$widget.css("-ms-transform")     ||
			$widget.css("-o-transform")      ||
			$widget.css("transform");
		
			matrix = [1,0,0,1];	
			if(css !== 'none' || css !== undefined) {
				m = css.split('(')[1].split(')')[0].split(',');
				
				for (var j = 0; j < 4; j++) {
					matrix[j] = parseFloat($.trim(m[j]));
				}
			}		
			
			widgetData = $widget.data("widget");
			widgetOptions = widgetData.options;
			
			widgetOptions.x = parseFloat($widget.css("left").replace("px"));
			widgetOptions.y = parseFloat($widget.css("top").replace("px"));
			widgetOptions.width = $widget.width();
			widgetOptions.height = $widget.height();
			widgetOptions.matrix = matrix;
			
			data.widgets.push({
				'id': widgetData.id,
				'type': widgetData.type,
				'options': widgetOptions
			});
		});
		
		
		// html		
		data.header_html = $('#editor .header').html();
		data.header_style = $('#editor .header').attr('style');
		data.footer_html = $('#editor .footer').html();
		data.footer_style = $('#editor .footer').attr('style');
		data.pages_html = $('#pages').html();
		data.pages_style = $('#pages').attr('style');
		//		data.pages = [];
		//		
		//		var page = {
		//			page: 1,
		//			body: $('#pages .body').html(),
		//			overlay: $('#pages .overlay').html()
		//		}
		//		
		//		data.pages.push(page);
		
		var href = baseUrl + '/admin/brochure/ajaxSave';
		
		if (templateId != null) {
			href += '?id=' + templateId;
		}
		
		console.log(data);
		
		ui.doAjax('POST', href, {
			data: JSON.stringify(data)
		}, onAjaxSaveSuccess);
	}
	
	function actionPreview() {
		window.open(baseUrl + '/admin/brochure/print/' + templateId);
	}
	
	function onAjaxSaveSuccess(response) {
		if (response.result == 'success') {
			templateId = response.id;
			
			window.alert('Saved');
		}
	}
	
	function loadTemplate(id) {
		if (id > 0) {
			var href = baseUrl + '/admin/brochure/ajaxLoad?id=' + id;
		
			ui.doAjax('GET', href, null, onAjaxLoadSuccess);
		}
	}
	
	function onAjaxLoadSuccess(response) {
		if (response.result == 'success') {
			var data = response.data;
			
			// set data
			templateId = data.id;
			name = data.name || 'Untitled Document';
			type = data.type || '';
			settings = $.extend({}, defaultSettings, data.settings);
			widgets = data.widgets || [];
			
			// set html
			$('#editor .header').html(data.header_html);
			$('#editor .header').attr('style', data.header_style);
			$('#editor .footer').html(data.footer_html);
			$('#editor .footer').attr('style', data.footer_style);
			
			
			// init widgets
			$.each(widgets, function(i, widgetData) {
				createWidget(widgetData);
			});
			
			// initEditor
			initEditor();
		}
	}
	
	function getDefaultX() {
		return defaultSettings.page.marginLeft * defaultSettings.dpm;
	}
	
	function getDefaultY() {
		return defaultSettings.page.marginTop * defaultSettings.dpm;
	}
	
	// TODO
	function addPageBreaks() {
	}
	
	function onToolClick(e) {
		e.preventDefault();
		
		var toolAction = $(this).attr('action');
		selectedTool = tools[toolAction];
		
		if ($.isFunction(selectedTool.action)) {
			selectedTool.action();
		}
	}
	
	function initEditor() {		
		$('#pages, #editor').width(settings.page.width * settings.dpm);
		$('#pages, #editor').height(settings.page.height * settings.dpm);
		$('#pages, #editor').css({
			'position': 'relative'
		});
		$('#pages .body').css({
			'padding-top': settings.page.marginTop * settings.dpm,
			'padding-right': settings.page.marginRight * settings.dpm,
			'padding-bottom': settings.page.marginBottom * settings.dpm,
			'padding-left': settings.page.marginLeft * settings.dpm
		});
		$('#pages .overlay').css({
			'position': 'absolute',
			'top': 0,
			'left': 0,
			'bottom': 0,
			'right': 0
		});
		
		$('#editor .header').height((settings.header.height - settings.header.marginTop) * settings.dpm);
		$('#editor .header').css({
			'padding-top': settings.header.marginTop * settings.dpm,
			'padding-right': settings.page.marginRight * settings.dpm,
			'padding-left': settings.page.marginLeft * settings.dpm
		});
		
		$('#editor .footer').height((settings.footer.height - settings.footer.marginBottom) * settings.dpm);
		$('#editor .footer').css({
			'padding-bottom': settings.footer.marginBottom * settings.dpm,
			'padding-right': settings.page.marginRight * settings.dpm,
			'padding-left': settings.page.marginLeft * settings.dpm
		});
		
		$editor.show();
	}
	
	function initToolbar() {
		
		var $tool;
		$.each(tools, function(toolAction, tool) {
			switch (tool.type) {
				case 'button':
					$tool = $('<div />');
					$tool
					.attr('title', tool.title)
					.attr('action', toolAction)
					.addClass('tool')
					.addClass('tool-' + toolAction)
					.text(tool.title);
					break;
				case 'separator':
					$tool = $('<div />')
					.addClass('tool-separator');
					break;
			}
			
			$tool.appendTo($toolbar);
		});
	}
	
	function onWidgetSelected(e, ui) {
		var data = $(ui.selected).data("widget");
		
		if ($.isFunction(data.onSelected)) {
			data.onSelected(e, ui);
		}
	}
	
	function onWidgetUnselected(e, ui) {
		var data = $(ui.unselected).data("widget");
		
		if ($.isFunction(data.onUnselected)) {
			data.onUnselected(e, ui);
		}
	}
	
	function onWidgetSelecting(e, ui) {
		var data = $(ui.selecting).data("widget");
		
		if ($.isFunction(data.onSelecting)) {
			data.onSelecting(e, ui);
		}
	}
	
	function onWidgetUnselecting(e, ui) {
		var data = $(ui.unselecting).data("widget");
		
		if ($.isFunction(data.onUnselecting)) {
			data.onUnselecting(e, ui);
		}
	}
	
	function initEventHandlers() {
		$('#toolbar').delegate('.tool', 'click', onToolClick);
		
		$('#editor').selectable({
			'filter': '.widget-selectable',
			'selecting': onWidgetSelecting,
			'selected': onWidgetSelected,
			'unselecting': onWidgetUnselecting,
			'unselected': onWidgetUnselected
		});
	}
	
	$(document).ready(function() {
		$editor = $('#editor');
		$toolbar = $('#toolbar');		
		$overlay = $('#pages .overlay');
		$content = $('#pages .body .content');
		
		$editor.hide();
		
		initToolbar();
		initEventHandlers();
		
		if (templateId > 0) {
			loadTemplate(templateId);
		} else {
			settings = defaultSettings;
			initEditor();
		}
	});
})(jQuery, propsage.ui);